/*
 * Copyright © 2016 CTODB.CN. All rights reserved.
 */

package cn.ctodb.notebook.wxapp.service.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public final class HttpUtils {

    private static final int readTimeOut = 10 * 1000;
    private static final int connectTimeout = 10 * 1000;

    private HttpUtils() {
    }

    // 向服务器发送post请求
    public static String postJson(String urlAddress, String params) {
        if (urlAddress == null || params == null) return "";
        try {
            URL url = new URL(urlAddress);
            HttpURLConnection uRLConnection = (HttpURLConnection) url.openConnection();
            uRLConnection.setDoInput(true);
            uRLConnection.setDoOutput(true);
            uRLConnection.setRequestMethod("POST");
            uRLConnection.setUseCaches(false);
            uRLConnection.setInstanceFollowRedirects(false);
            uRLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            uRLConnection.setReadTimeout(readTimeOut);
            uRLConnection.setConnectTimeout(connectTimeout);
            uRLConnection.connect();
            DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
            out.write(params.getBytes("UTF-8"));
            out.close();
            return getResponse(uRLConnection);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getResponse(HttpURLConnection uRLConnection) throws IOException {
        InputStream is = uRLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String response = "";
        String readLine;
        while ((readLine = br.readLine()) != null) {
            response = response + readLine;
        }
        uRLConnection.disconnect();
        is.close();
        br.close();

        return response;
    }

    public static String get(String urlAddress) {
        try {
            URL url = new URL(urlAddress);
            HttpURLConnection uRLConnection = (HttpURLConnection) url.openConnection();
            uRLConnection.setDoInput(true);
            uRLConnection.setDoOutput(true);
            uRLConnection.setRequestMethod("POST");
            uRLConnection.setUseCaches(false);
            uRLConnection.setInstanceFollowRedirects(false);
            uRLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            uRLConnection.setReadTimeout(readTimeOut);
            uRLConnection.setConnectTimeout(connectTimeout);
            uRLConnection.connect();
            DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
            out.close();
            return getResponse(uRLConnection);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
